package com.lagou.edu.config;

import org.springframework.util.ReflectionUtils;
import org.springframework.web.WebApplicationInitializer;

import javax.servlet.ServletContainerInitializer;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.HandlesTypes;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

/**
 * 容器在启动应用的时候，会扫描当前应用每一个jar包里面
 * META-INF/services/javax.servlet.ServletContainerInitializer指定的实现类，启动并运行这个实现类的方法；
 * 传入感兴趣的类型；
 */
@HandlesTypes({MyWebApplicationInitializer.class})
public class MySpringServletContainerInitializer implements ServletContainerInitializer {
    public void onStartup(Set<Class<?>> set, ServletContext servletContext) throws ServletException {
        //用于存储实例化的类
        List<WebApplicationInitializer> initializers = new LinkedList<WebApplicationInitializer>();

        if (set != null) {
            for (Class<?> aClass : set) {
                if (!aClass.isInterface() && !Modifier.isAbstract(aClass.getModifiers()) && WebApplicationInitializer.class.isAssignableFrom(aClass)) {
                    try {
                        //实例化该类，并加入到initializers集合中
                        initializers.add((WebApplicationInitializer) ReflectionUtils.accessibleConstructor(aClass).newInstance());
                    } catch (InstantiationException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    } catch (NoSuchMethodException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        for (WebApplicationInitializer initializer : initializers) {
            //调用其onStartup方法
            initializer.onStartup(servletContext);
        }
    }
}
